// ignore_for_file: prefer_const_constructors, prefer_const_literals_to_create_immutables, must_be_immutable
import 'dart:async';
import 'dart:math';

import 'package:flutter/material.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:in_app_purchase/in_app_purchase.dart';
import 'package:junyeyishu/ui/home/QGNFTDetailPage.dart';

import 'package:junyeyishu/utils/utils.dart';
import 'package:junyeyishu/widgets/QGButton.dart';

class QGReviewSaleDetailPage extends QGNFTDetailPage {
  String id;
  QGReviewSaleDetailPage({super.key, required this.id}) : super(id: id);
  @override
  State<QGNFTDetailPage> createState() => _QGReviewSaleDetailPageState();
}

class _QGReviewSaleDetailPageState extends QGNFTDetailPageState {
  StreamSubscription<dynamic>? subscription;
  ProductDetails? iapProduct;

  @override
  void dispose() {
    subscription?.cancel();
    super.dispose();
  }

  @override
  void initState() {
    super.initState();

    InAppPurchase.instance.isAvailable().then((value) {
      final Stream purchaseUpdated = InAppPurchase.instance.purchaseStream;
      subscription = purchaseUpdated.listen((purchaseDetailsList) {
        iap_update(purchaseDetailsList);
      }, onDone: () {
        subscription?.cancel();
      }, onError: (error) {
        print(error);
      });

      InAppPurchase.instance.queryProductDetails({'qiange.shucang.888'}).then(
          (ProductDetailsResponse response) {
        if (response.notFoundIDs.isNotEmpty) {
          return;
        }
        iapProduct = response.productDetails[0];
      });
    });
  }

  iap_update(List<PurchaseDetails> purchaseDetailsList) async {
    for (var purchaseDetails in purchaseDetailsList) {
      switch (purchaseDetails.status) {
        case PurchaseStatus.pending:
          EasyLoading.show(
              indicator: CircularProgressIndicator(
                  strokeWidth: 1, color: Colors.white));
          break;
        case PurchaseStatus.canceled:
          EasyLoading.dismiss();
          toast("已取消");
          break;
        case PurchaseStatus.error:
          EasyLoading.dismiss();
          toast("未知错误，请稍候重试");
          break;
        case PurchaseStatus.restored:
          EasyLoading.dismiss();
          toast("success");
          break;
        case PurchaseStatus.purchased:
          EasyLoading.dismiss();
          toast("购买成功！");
          break;
      }

      if (purchaseDetails.pendingCompletePurchase) {
        await InAppPurchase.instance.completePurchase(purchaseDetails);
      }
    }
  }

  @override
  handleData(data) {
    if (inReview()) {
      data?["price"] = "888";
    }
  }

  @override
  url() {
    return url_market_collectionInfo;
  }

  @override
  param() {
    return {"cid": widget.id};
  }

  @override
  buildOwner() {
    return buildIntroChainInfoItem(title: "拥有者", value: data?["owner"] ?? "");
  }

  @override
  buildIntroNo() {
    return Container(
      margin: EdgeInsets.only(top: 10.rpx),
      padding: EdgeInsets.fromLTRB(10.rpx, 15.rpx, 10.rpx, 15.rpx),
      decoration: BoxDecoration(
        borderRadius: BorderRadius.circular(10.rpx),
        color: Color(0xFFF8F8F6),
      ),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        Text(
          '产品编号1',
          style: TextStyle(
              color: Color(0xFF111111),
              fontSize: 14.rpx,
              fontWeight: FontWeight.normal),
        ),
        Text(
          '#${data?["nft_no"]}/${data?["total"]}',
          style: TextStyle(
              color: Color(0xFF111111),
              fontSize: 14.rpx,
              fontWeight: FontWeight.bold),
        ),
      ]),
    );
  }

  @override
  buildBottom() {
    return Container(
      width: kScreenWidth,
      color: Color(0xFFFFFFFF),
      padding:
          EdgeInsets.fromLTRB(10.rpx, 10.rpx, 10.rpx, max(kSafeBottom, 10)),
      child: Row(mainAxisAlignment: MainAxisAlignment.spaceBetween, children: [
        Text(
          '￥${data?["price"]}',
          style: TextStyle(
              color: Color(0xFF111111),
              fontSize: 26.rpx,
              fontWeight: FontWeight.bold),
        ),
        Flexible(
          child: Container(
              alignment: Alignment.center,
              height: 44.rpx,
              width: 210.rpx,
              child: QGButton(
                title: "去支付",
                enable: true,
                onTap: onPay,
              )),
        )
      ]),
    );
  }

  @override
  pid() {
    return data?["pid"];
  }

  @override
  onPay() async {
    if (!User.isLogin) {
      Navigator.of(context).pushNamed(PageLogin);
      return;
    }

    if (!inReview()) return;

    InAppPurchase.instance.buyConsumable(
        purchaseParam: PurchaseParam(
            productDetails: iapProduct ??
                ProductDetails(
                    id: "qiange.shucang.888",
                    title: "藏品",
                    description: "千格数字藏品",
                    price: "¥888",
                    currencyCode: 'CNY',
                    currencySymbol: "¥",
                    rawPrice: 888)));
  }
}
